const express = require('express');
const router = express.Router();
const axios = require('axios')
const querystring = require('querystring');
const config = require('../config/config')
const db = require('../db/index')
// 微信验证接口
router.get('/', (req, res) => {
    // 获取微信服务器发送的参数
    const { signature, timestamp, nonce, echostr } = req.query;
    // 你的token，需要和微信后台配置的一致
    const token = config.token;
    // 按照微信的规则进行校验
    const arr = [token, timestamp, nonce].sort().join('');
    const sha1 = require('crypto').createHash('sha1');
    const hash = sha1.update(arr).digest('hex');

    // 校验签名是否一致
    if (hash === signature) {
        // 如果一致，返回echostr
        res.send(echostr);
    } else {
        // 如果不一致，返回错误信息
        res.status(400).send('Invalid signature');
    }
})

router.get('/Accesstoken', (req, res) => {
    const { AppID, AppSecret, token } = config
    axios.get('https://api.weixin.qq.com/cgi-bin/token', {
        params: {
            grant_type: 'client_credential',
            appid: AppID,
            secret: AppSecret
        }
    }).then(result => {
        res.send({
            code: 200,
            data: result.data
        })
    })
})

router.post('/set', async (req, res) => {
    const { url } = config
    const { data } = await axios.get(url + '/wechat/Accesstoken')
    db.query(`UPDATE t_token SET token = ? where id = ?`, [data.data.access_token, 1], (err, result) => {
        if (err) return res.send({ code: 500, message: err.message })
        res.send({
            code: 200,
            data: {}
        })
    })
}
)



module.exports = router